package com.right.health.app.ui.household;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.magic.basic.activity.BaseFragmentActivity;
import com.magic.basic.utils.CollectionUtil;
import com.magic.basic.utils.TimeUtil;
import com.magic.basic.utils.ToastUtil;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.base.BasePresenterFragment;
import com.right.health.app.bean.BloodSugarBean;
import com.right.health.app.bean.BloodSugarResponse;
import com.right.health.app.net.HouseholdApi;
import com.right.health.app.ui.household.adapter.BloodSugarLatestAdapter;
import com.right.health.app.ui.household.fragment.BloodSugarChartFragment;
import com.right.health.app.widget.HealthSeekBar;

import java.util.ArrayList;
import java.util.List;

/*
 * Created by hopeliao on 2019-10-02
 *
 * 血糖
 */
public class BloodSugarActivity extends BaseFragmentActivity implements View.OnClickListener,
        HealthSeekBar.OnSeekBarChangeListener, OnHttpListener {

    private static final int HTTP_CODE_ADD = 1;
    private static final int HTTP_CODE_LATEST = 2;
    private static final int TAB_BEFORE_MEAL = 0;
    private static final int TAB_AFTER_MEAL = 1;

    private TextView[] mTvs;

    private TextView mBloodSugarValueTv, mLatestDateTv;

    private RecyclerView mRecyclerView;

    private float mLastBloodSugarValue;

    private int mLastType, mMealType;

    private TabLayout mTabLayout;

    private Fragment mFragment;

    private String mFragmentType;

    private HouseholdApi mHouseholdApi;
    private BloodSugarLatestAdapter mAdapter;
    private List<BloodSugarBean> mLatestList = new ArrayList<>();

    @Override
    public void onCreate(Bundle bundle, String s) {
        setContentView(R.layout.blood_sugar);
    }

    @Override
    public void findView() {
        TextView timeTv = (TextView) findViewById(R.id.tv_time);
        timeTv.setText(TimeUtil.convertTime("yyyy-MM-dd", System.currentTimeMillis()));
        mTabLayout = findViewById(R.id.tb_meals);
        mTabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int index = tab.getPosition();
                findViewById(R.id.rl_meal_time).setVisibility(index == 0 || index == 4 ? View.INVISIBLE : View.VISIBLE);
                mLastType = index;
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        findViewById(R.id.tv_save).setOnClickListener(this);

        mBloodSugarValueTv = (TextView) findViewById(R.id.tv_blood_sugar_value);
        mBloodSugarValueTv.setText("0.0");
        mLatestDateTv = findViewById(R.id.tv_data_latest);

        mTvs = new TextView[5];
        mTvs[0] = (TextView) findViewById(R.id.tv_before_meal);
        mTvs[1] = (TextView) findViewById(R.id.tv_after_meal);
        mTvs[2] = findViewById(R.id.tv_today);
        mTvs[3] = findViewById(R.id.tv_week);
        mTvs[4] = findViewById(R.id.tv_month);
        for (TextView tv : mTvs) {
            tv.setOnClickListener(this);
        }
        switchMeal(TAB_BEFORE_MEAL);

        mRecyclerView = findViewById(R.id.rv_latest);
        mAdapter = new BloodSugarLatestAdapter(this);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mAdapter);
        HealthSeekBar seekBar = (HealthSeekBar) findViewById(R.id.seekbar);
        seekBar.setTextIndex(4, 9);
        seekBar.setOnSeekBarChangeListener(this);
    }

    @Override
    public void initialize() {
        mHouseholdApi = new HouseholdApi();
        mHouseholdApi.setListener(this);
        mHouseholdApi.addRequestCode(HTTP_CODE_LATEST);
        mHouseholdApi.getLatestBloodSugar();
        for (int i = 0; i < 8; i++) {
            BloodSugarBean bean = new BloodSugarBean();
            mLatestList.add(bean);
        }
        mAdapter.setData(mLatestList);
        mTvs[2].setSelected(true);
        showFragment(BloodSugarResponse.TYPE_DAY);
    }

    private void showFragment(String type) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction= manager.beginTransaction();
        if (mFragment != null) {
            transaction.hide(mFragment);
        }
        Fragment fragment = manager.findFragmentByTag(type);
        if (fragment == null) {
            fragment = BloodSugarChartFragment.newInstance(type);
            transaction.add(R.id.frameLayout, fragment, type);
        } else {
            transaction.show(fragment);
        }
        mFragment = fragment;
        mFragmentType = type;
        transaction.commit();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_before_meal: //餐前
                switchMeal(TAB_BEFORE_MEAL);

                break;
            case R.id.tv_after_meal: //餐后
                switchMeal(TAB_AFTER_MEAL);
                break;
            case R.id.tv_save: //保存数据
                send2Net();
                break;
            case R.id.tv_today: //今天
                if (!TextUtils.equals(mFragmentType,BloodSugarResponse.TYPE_DAY)) {
                    switchTimeTab(2);
                    showFragment(BloodSugarResponse.TYPE_DAY);
                }
                break;
            case R.id.tv_week: //周
                if (!TextUtils.equals(mFragmentType,BloodSugarResponse.TYPE_WEEK)) {
                    switchTimeTab(3);
                    showFragment(BloodSugarResponse.TYPE_WEEK);
                }
                break;
            case R.id.tv_month: //月
                if (!TextUtils.equals(mFragmentType,BloodSugarResponse.TYPE_MONTH)) {
                    switchTimeTab(4);
                    showFragment(BloodSugarResponse.TYPE_MONTH);
                }
                break;
        }
    }

    private void switchTimeTab(int index) {
        for (int i = 2; i <5 ; i++) {
            mTvs[i].setSelected(i==index);
        }
    }

    private void send2Net() {
        if (mLastBloodSugarValue == 0) {
            ToastUtil.show(this, "请选择您的血糖值");
            return;
        }
        mHouseholdApi.addRequestCode(HTTP_CODE_ADD);
        mHouseholdApi.addBloodSugar(mLastBloodSugarValue, mLastType, mMealType);
    }


    private void switchMeal(int tab) {
        for (int i = 0; i <2; i++) {
            mTvs[i].setSelected(i == tab);
        }
        mMealType = tab;
    }

    private void refreshFragmentData() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                ((BasePresenterFragment) fragment).refreshData();
            }
        }
    }

    @Override
    public void onProgressChanged(HealthSeekBar seekBar, float progress, boolean fromUser) {
        float value = progress * seekBar.getMaxValue();
        float text = (float) (Math.round(value * 10)) / 10;
        mLastBloodSugarValue = text;
        mBloodSugarValueTv.setText(String.valueOf(text));
    }

    @Override
    public void onResponse(Request request, Response response) {
        if (response.isResponseFail()) {
            ToastUtil.show(this, "请稍后再试");
        } else {
            if (request.requestCode == HTTP_CODE_ADD) {
                ToastUtil.show(this, "保存成功");
                refreshFragmentData();
                mHouseholdApi.addRequestCode(HTTP_CODE_LATEST);
                mHouseholdApi.getLatestBloodSugar();
            } else if (request.requestCode == HTTP_CODE_LATEST) {
                if (response.targetData instanceof BloodSugarResponse) {
                    BloodSugarResponse bloodPressureResponse = response.cast(BloodSugarResponse.class);
                    if (bloodPressureResponse.sugars != null) {
                        dealLatestList(bloodPressureResponse.sugars);
                    }
                }
            }
        }
    }

    private void dealLatestList(List<BloodSugarBean> sugars) {
        if (!CollectionUtil.isEmpty(sugars)) {
            String latestDate = "";
            if (!TextUtils.isEmpty(sugars.get(0).getCreatetime())) {
                try {
                    latestDate = sugars.get(0).getCreatetime().substring(0, 11);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mLatestDateTv.setText(latestDate);

            for (BloodSugarBean bean : sugars) {
                int position = -1;
                switch (bean.getSugartimetype()) {
                    case "0":
                        position = 0;
                        break;
                    case "1":
                        if (TextUtils.equals(bean.getFoodstatus(), "0")) {
                            position = 1;
                        } else if (TextUtils.equals(bean.getFoodstatus(), "0")) {
                            position = 2;
                        }
                        break;
                    case "2":
                        if (TextUtils.equals(bean.getFoodstatus(), "0")) {
                            position = 3;
                        } else if (TextUtils.equals(bean.getFoodstatus(), "0")) {
                            position = 4;
                        }
                        break;
                    case "3":
                        if (TextUtils.equals(bean.getFoodstatus(), "0")) {
                            position = 5;
                        } else if (TextUtils.equals(bean.getFoodstatus(), "0")) {
                            position = 6;
                        }
                        break;
                    case "4":
                        position = 7;
                        break;
                }
                if (position != -1) {
                    mLatestList.set(position, bean);
                }
            }
            mAdapter.setData(mLatestList);
        }
    }
}
